package com.booter.zookeeper.serializer;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class UnsafeByteArrayOutputStream extends OutputStream {
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    protected byte buf[];

    protected int count;

    public UnsafeByteArrayOutputStream() {
        this(32);
    }

    public UnsafeByteArrayOutputStream(int size) {
        if (size < 0) {
            throw new IllegalArgumentException(
                    "Negative initial size: " + size);
        }
        this.buf = new byte[size];
    }

    private void ensureCapacity(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - this.buf.length > 0) {
            this.grow(minCapacity);
        }
    }

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = this.buf.length;
        int newCapacity = oldCapacity << 1;
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        if (newCapacity - UnsafeByteArrayOutputStream.MAX_ARRAY_SIZE > 0) {
            newCapacity = UnsafeByteArrayOutputStream.hugeCapacity(minCapacity);
        }
        this.buf = Arrays.copyOf(this.buf, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) {
            throw new OutOfMemoryError();
        }
        return minCapacity > UnsafeByteArrayOutputStream.MAX_ARRAY_SIZE
                ? Integer.MAX_VALUE : UnsafeByteArrayOutputStream.MAX_ARRAY_SIZE;
    }

    @Override
    public void write(int b) {
        this.ensureCapacity(this.count + 1);
        this.buf[this.count] = (byte) b;
        this.count += 1;
    }

    @Override
    public void write(byte b[], int off, int len) {
        if (off < 0 || off > b.length || len < 0 || off + len - b.length > 0) {
            throw new IndexOutOfBoundsException();
        }
        this.ensureCapacity(this.count + len);
        System.arraycopy(b, off, this.buf, this.count, len);
        this.count += len;
    }

    public void writeTo(OutputStream out) throws IOException {
        out.write(this.buf, 0, this.count);
    }

    public void reset() {
        this.count = 0;
    }

    public byte toByteArray()[] {
        return Arrays.copyOf(this.buf, this.count);
    }

    public int size() {
        return this.count;
    }

    @Override
    public String toString() {
        return new String(this.buf, 0, this.count);
    }

    public String toString(String charsetName)
            throws UnsupportedEncodingException {
        return new String(this.buf, 0, this.count, charsetName);
    }

    @Override
    public void close() {
        // EMPTY
    }

}
